<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            v-model="usersQueryParam.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button> </el-input
        ></el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserBtn">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table style="width: 100%" :data="UserListData" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="usersTableSwitchStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="userEditBtn(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="userDelete(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="allotRolesBtn(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="usersHandleSizeChange"
        @current-change="userhandleCurrentChange"
        :current-page="usersQueryParam.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="usersQueryParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="UserListTotal"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="userAddDialogVisible"
      width="50%"
      @close="addUserDialogCb"
    >
      <el-form
        label-width="80px"
        :model="userAddForm"
        :rules="userAddFormRules"
        ref="userAddFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userAddForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userAddForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userAddForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userAddForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userAddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="userEditDialogVisible"
      width="50%"
    >
      <!-- 表单区域 -->
      <el-form
        :rules="userAddFormRules"
        ref="userEditFormRef"
        :model="userEditForm"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="userEditForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userEditForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userEditForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="usersAllotRolesDialogVisible"
      width="50%"
      @close="usersAllotRolesDialogVisibleClose"
    >
      <p>当前用户名：{{ rolesInfo.username }}</p>
      <p>当前的角色：{{ rolesInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectValueId" placeholder="请选择">
          <el-option
            v-for="item in usersRolesListData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="usersAllotRolesDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="AllotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义手机验证规则
    const checkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }

    // 自定义邮箱验证规则
    const checkEmail = (rule, value, cb) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('邮箱不正确'))
      }
    }
    return {
      // 请求用户列表需要的参数
      usersQueryParam: {
        query: '',
        pageNum: 1,
        pageSize: 2
      },
      // 用户列表总数
      UserListTotal: 0,
      // 服务器返回用户列表的数据
      UserListData: [],
      // 控制添加用户对话框显示与隐藏
      userAddDialogVisible: false,
      // 控制分配角色对话框显示与隐藏
      usersAllotRolesDialogVisible: false,
      // 用户添加表单数据对象
      userAddForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户添加表单验证规则
      userAddFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框显示与隐藏
      userEditDialogVisible: false,
      // 修改表单数据对象
      userEditForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色信息
      rolesInfo: [],
      // select选择器双向数据绑定的值
      selectValueId: '',
      // 分配角色列表
      usersRolesListData: []
    }
  },
  methods: {
    // 获取用户列表数据
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: {
          query: this.usersQueryParam.query,
          pagenum: this.usersQueryParam.pageNum,
          pagesize: this.usersQueryParam.pageSize
        }
      })
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //   服务器返回用户列表的数据
      this.UserListData = res.data.users
      //   服务器返回用户列表总数
      this.UserListTotal = res.data.total
    },
    // 每页条数发生改变的时候会触发
    usersHandleSizeChange(newSize) {
      // 将改变后的每页显示多少条数据做更新
      this.usersQueryParam.pageSize = newSize
      // 重新发送请求获取数据
      this.getUsersList()
    },
    // 点击某一页会触发
    userhandleCurrentChange(newCurrent) {
      // 改变后的某一页做更新
      this.usersQueryParam.pageNum = newCurrent
      // 重新发送请求获取数据
      this.getUsersList()
    },
    // 当状态开关发生改变的时候触发
    async usersTableSwitchStatus(presentStatus) {
      const { data: res } = await this.$http.put(
        `users/${presentStatus.id}/state/${presentStatus.mg_state}`
      )
      //   console.log(res)
      if (res.meta.status !== 200) {
        presentStatus.mg_state = !presentStatus.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success(res.meta.msg)
    },
    // 添加用户按钮
    addUserBtn() {
      this.userAddDialogVisible = true
    },
    // 关闭添加用户对话框回调函数
    addUserDialogCb() {
      this.$refs.userAddFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      // 发送请求添加用户之前预验证
      this.$refs.userAddFormRef.validate(async validata => {
        if (!validata) return false
        // 发送请求
        const { data: res } = await this.$http.post('users', this.userAddForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 成功提示框
        this.$message.success(res.meta.msg)
        // 关闭添加用户对话框
        this.userAddDialogVisible = false
        // 重新发送请求刷新页面
        this.getUsersList()
      })
    },
    // 编辑按钮
    async userEditBtn(row) {
      const { data: res } = await this.$http.get(`users/${row.id}`)
      this.userEditForm.id = res.data.id
      this.userEditForm.username = res.data.username
      this.userEditForm.email = res.data.email
      this.userEditForm.mobile = res.data.mobile
      // 控制修改用户对话框显示与隐藏
      this.userEditDialogVisible = true
    },
    // 编辑用户
    editUser() {
      // 预验证
      this.$refs.userEditFormRef.validate(async vadata => {
        if (!vadata) return false
        const { data: res } = await this.$http.put(
          `users/${parseInt(this.userEditForm.id)}`,
          this.userEditForm
        )
        // 判断服务器返回的状态是否一致
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 控制修改用户对话框显示与隐藏
        this.userEditDialogVisible = false
        // 重新发送请求刷新页面
        this.getUsersList()
      })
    },
    // 删除用户
    async userDelete(id) {
      const confirmReceive = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmReceive !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发送请求
      const { data: res } = await this.$http.delete('users/' + id)
      // 判断状态码是否一致
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 重新发送请求刷新页面
      this.getUsersList()
    },
    // 分配角色Btn
    async allotRolesBtn(roles) {
      this.rolesInfo = roles
      const { data: res } = await this.$http.get('roles')
      this.usersRolesListData = res.data
      // 显示分配角色对话框
      this.usersAllotRolesDialogVisible = true
    },
    // 分配新角色
    async AllotRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.rolesInfo.id}/role`,
        {
          rid: this.selectValueId
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 关闭分配角色对话框
      this.usersAllotRolesDialogVisible = false
      // 重新发送请求数据
      this.getUsersList()
    },
    // 关闭分配角色对话框回调
    usersAllotRolesDialogVisibleClose() {
      this.selectValueId = ''
    }
  },
  created() {
    this.getUsersList()
  }
}
</script>

<style lang="less" scoped></style>
